
package com.xkw.autocode.web.codeexport.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xkw.autocode.base.BaseController;
import com.xkw.autocode.code.CodeExportService;
import com.xkw.autocode.jdbc.entity.ColumnEntity;
import com.xkw.autocode.jdbc.entity.TableEntity;
import com.xkw.autocode.jdbc.mysql.MysqlSqlParser;
import com.xkw.autocode.logaspect.SysLog;
import com.xkw.autocode.util.ZipCompressor;
import com.xkw.autocode.web.codeexport.CodeExportUrlUtil;
import com.xkw.autocode.web.codeexport.ao.CodeExportAo;
import com.xkw.autocode.web.common.Result;
import com.xkw.autocode.web.databaseconfig.ao.DatabaseConfigAo;
import com.xkw.autocode.web.templateconfig.ao.TemplateConfigAo;

/**
 * 首页
 */
@Controller
public class CodeExportController extends BaseController {

	@Autowired
	private DatabaseConfigAo databaseConfigAo;

	@Autowired
	private TemplateConfigAo templateConfigAo;

	@Autowired
	private CodeExportService codeExportService;

	@Autowired
	private CodeExportAo codeExportAo;

	@GetMapping(value = CodeExportUrlUtil.TO_EXPORT_FROM_DB)
	public ModelAndView toExportFromDb() {
		ModelAndView modelAndView = new ModelAndView();

		// 查询所有的DB配置
		modelAndView.addObject("databaseConfigs", databaseConfigAo.queryList(null));

		// 查询所有模板
		modelAndView.addObject("templateConfigs", templateConfigAo.queryAll());

		modelAndView.setViewName("codeExport/exportFromDb");
		return modelAndView;
	}

	@GetMapping(value = CodeExportUrlUtil.TO_EXPORT_FROM_SQL)
	public ModelAndView toExportFromSql() {
		ModelAndView modelAndView = new ModelAndView();

		// 查询所有模板
		modelAndView.addObject("templateConfigs", templateConfigAo.queryAll());

		modelAndView.setViewName("codeExport/exportFromSql");
		return modelAndView;
	}

	@SysLog(option="查看",value="查看模板配置关键字")
	@GetMapping(value = CodeExportUrlUtil.TO_KEYWORDS_DEMO)
	public ModelAndView toKeywordsDemo() {
		ModelAndView modelAndView = new ModelAndView();

		TableEntity table = new TableEntity();
		table.setTableName("system_log");
		table.setComments("系统操作日志");

		List<ColumnEntity> columns = new ArrayList<>();
		columns.add(new ColumnEntity("id", "bigint", "主键Id"));
		columns.add(new ColumnEntity("operation_time", "bigint", "操作时间"));
		columns.add(new ColumnEntity("log_content", "varchar(200)", "日志内容"));
		table.setColumns(columns);

		modelAndView.addObject("keywordsDemos", codeExportService.getKeywordsMap(table, "com.system.log"));

		modelAndView.setViewName("codeExport/keywordsDemo");

		return modelAndView;
	}

	/**
	 * 根据数据库查询数据库中的表
	 */
	@RequestMapping(value = CodeExportUrlUtil.QUERY_TABLE_FROM_DB)
	@ResponseBody
	public List<TableEntity> queryTableFromDb(HttpServletRequest request, Long databaseId) {

		return codeExportAo.queryTables(databaseId);
	}

	/**
	 * 根据数据库查询数据库中的表
	 */
	@RequestMapping(value = CodeExportUrlUtil.ANALYSIS_TABLE_FROM_SQL)
	@ResponseBody
	public List<TableEntity> analysisTableFromSql(HttpServletRequest request, String sqlContent) {

		if (StringUtils.isEmpty(sqlContent)) {
			return Collections.emptyList();
		}

		try {
			return new MysqlSqlParser().getTableFromSql(sqlContent);
		} catch (Exception e) {
			return Collections.emptyList();
		}
	}

	/**
	 * 根据数据库中的表结构导出
	 * 
	 * @throws IOException
	 */
	@SysLog(option="导出",value="根据数据库导出代码")
	@RequestMapping(value = CodeExportUrlUtil.DO_EXPORT_FROM_DB)
	public void doExportFromDb(HttpServletRequest request, HttpServletResponse response, Long databaseId,
			String javaPakeage, Long templateId, String tableNames) throws IOException {

		this.doExport(request, response, databaseId, null, javaPakeage, templateId, tableNames);
	}

	/**
	 * 根据Sql语句的表结构导出
	 * 
	 * @throws IOException
	 */
	@SysLog(option="导出",value="根据Sql导出代码")
	@RequestMapping(value = CodeExportUrlUtil.DO_EXPORT_FROM_SQL)
	public void doExportFromSql(HttpServletRequest request, HttpServletResponse response, String sqlContent,
			String javaPakeage, Long templateId, String tableNames) throws IOException {

		this.doExport(request, response, null, sqlContent, javaPakeage, templateId, tableNames);
	}

	/**
	 * 根据路径导导出
	 * 
	 * @throws IOException
	 */
	@SysLog(option="导出",value="预览页面导出代码")
	@RequestMapping(value = CodeExportUrlUtil.DO_EXPORT_FROM_PATH)
	public void doExportFromPath(HttpServletRequest request, HttpServletResponse response) throws IOException {
		this.doExport(request, response, null, null, null, null, null);
	}

	public void doExport(HttpServletRequest request, HttpServletResponse response, Long databaseId, String sqlContent,
			String javaPakeage, Long templateId, String tableNames) throws IOException {

		String filePath = null;

		// 代码所在路径
		String codeFullPath = request.getParameter("codeFullPath");
		if (StringUtils.isNotEmpty(codeFullPath)) {

			String zipFilePath = codeFullPath + ".zip";
			ZipCompressor compress = new ZipCompressor(zipFilePath);
			compress.compress(codeFullPath);
			filePath = new File(zipFilePath).getAbsolutePath();

		} else {
			filePath = codeExportService.doExport(databaseId, sqlContent, tableNames, templateId, javaPakeage);
		}

		if (filePath != null) {
			String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);

			super.downLoadFile(filePath, response, "code_db" + "_" + fileName, "zip", true);
		}
	}

	/**
	 * 预览导出的文件
	 * 
	 * @throws IOException
	 */
	@SysLog(option="预览",value="预览生成的代码")
	@RequestMapping(value = CodeExportUrlUtil.VIEW_EXPORT)
	@ResponseBody
	public Result viewExport(HttpServletRequest request, HttpServletResponse response, Long databaseId,
			String sqlContent, String javaPakeage, Long templateId, String tableNames) {

		String filePath = codeExportService.doExport(databaseId, sqlContent, tableNames, templateId, javaPakeage,
				false);
		return Result.ok().put("filePath", filePath.replaceAll("\\\\", "/"));
	}
}
